﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Web.Infrastructure.Models;

namespace Web.Infrastructure
{
    [ValidateInput(false)]
    public class FrontendController : Controller
    {
        public virtual ActionResult BackBoneView(string viewName, object model)
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView(viewName, model);
            }
            return View(MVC.Shared.Views.Empty);
        }

        public virtual ActionResult BackBoneJson(object model)
        {
            if (Request.IsAjaxRequest())
            {
                return Json(model, JsonRequestBehavior.AllowGet);
            }
            return View(MVC.Shared.Views.Empty);
        }

        public virtual ActionResult BackBoneView(string viewName)
        {
            if (Request.IsAjaxRequest())
            {
                return PartialView(viewName);
            }
            return View(MVC.Shared.Views.Empty);
        }

        public IEnumerable<ErrorModel> GetErrors
        {
            get
            {
                var keys = ModelState.Select(x => x.Key);
                var errors = new List<ErrorModel>();
                foreach (var key in keys)
                {
                    var errorsForKey =
                        ModelState.Where(x => x.Key == key).Select(x => x.Value).SelectMany(x => x.Errors).Select(
                            x => new ErrorModel
                            {
                                Key = key,
                                Message = x.ErrorMessage
                            });
                    errors.AddRange(errorsForKey);
                }
                return errors;
            }
        }
    }
}